<template>
  <Drawer v-model:visible="visible" :title="title" width="100%" :destroyOnClose="true" placement="right">
    <div class="md:my-5">
      <Card>
        <CceRuleForm ref="cceRuleRef" @submit="addBasicParam"></CceRuleForm>
      </Card>
    </div>

    <div class="absolute bottom-10 right-8">
      <Button style="margin-right: 8px; font-weight: bolder" @click="closeDrawer">取消</Button>
      <Button type="primary" style="font-weight: bolder" @click="submitHandler">确定</Button>
    </div>
  </Drawer>
</template>

<script lang="ts" setup>
import { Drawer, Button, message } from 'ant-design-vue';
import { ref } from 'vue';
import { Card } from 'ant-design-vue';
import { createAlertRule, editAlertRule, viewCceRuleDetail } from '/@/api/maintenance-center/alarm/alarm';
import CceRuleForm from '/@/views/maintenance-center/alarm-rule/new-cce-rule/components/cceRuleForm.vue';

const emit = defineEmits(['success']);
const visible = ref<boolean>(false);
const title = ref('');
const cceRuleRef = ref();
const isThreshold = ref(null);
const params = ref({});
let result = {};

const showDrawer = async (record: Recordable, type: string) => {
  if (type === 'create') {
    title.value = '创建CCE告警规则';
    isThreshold.value = null;
    visible.value = true;
  } else if (type === 'edit') {
    title.value = '编辑CCE告警规则';
    let params = {
      alarmRuleId: record.alarmRuleId,
    };
    visible.value = true;
    result = await viewCceRuleDetail(params);
    cceRuleRef.value.setFormValue(result);
  }
};
const closeDrawer = async () => {
  visible.value = false;
};

async function addBasicParam(record: Recordable) {
  params.value = await Object.assign(params.value, record.value);
  let res;
  if (title.value === '编辑CCE告警规则') {
    res = await editAlertRule(params.value);
  } else {
    res = await createAlertRule(params.value);
  }
  message.info(res);
  emit('success');
  closeDrawer();
}

const submitHandler = async () => {
  cceRuleRef.value.handleSubmit();
};

defineExpose({ showDrawer });
</script>